package alexandria.dashboard.connector.agilezen
import alexandria.dashboard.entity.*
/**
 * AgileZen Connector Service
 *
 * Provides a RESTful client implementation for obtaining remote data through management tool for agile projects with Lean called AgileZen
 *
 * @version 0.5
 * @author  Samuel Rodrigues
 * @author  Vinícius Rodrigues
 */

class AgileZenConnectorService {


    static transactional = true
    def apiKey

    /**
     * setConfig Method
     *
     * @param   Receive the settings and set the token value for the selected account
     * @author  Samuel Rodrigues
     */
    def setConfig(Map cfg) {
        this.apiKey = cfg.token
    }

    /**
     * getData Method
     *
     * @param   Receives String with a URI Path which complements the REST request through HTTPBuilder
     * @return  Returns a JSON with the requested resource corresponds to the URI Path
     * @author  Samuel Rodrigues
     * @author  Vinícius Rodrigues
     */
    private getData(String uriPath, String query=null) {
        def http = new groovyx.net.http.HTTPBuilder("https://agilezen.com")
        http.request(groovyx.net.http.Method.GET, groovyx.net.http.ContentType.JSON) {
            uri.path = uriPath
			if(query)
				uri.query = [with: query]
            headers.'X-Zen-ApiKey' =  apiKey
            response.success = { resp, json -> return json }
        }
    }

    /**
     * listProjects Method
     *
     * Takes the information registered in AgileZen projects, and maps to the ProjectService convert into a list of Project objects
     *
     * @return  List of Projects objects
     * @see     alexandria.dashboard.entity.ProjectService
     * @author  Samuel Rodrigues
     * @author  Vinícius Rodrigues
     */
    def listProjects() {
        def json = getData("/api/v1/projects")

        List projects = []
        json.items.each {
            def project = new Project(
                externalId: it.id,
                name: it.name,
                description: it.description,
                owner: it.owner.name
            )
            projects.add(project)
        }
        return projects
    }

    /**
     * getProject Method
     *
     * Get a specific project registered in AgileZen, and maps to the ProjectService convert into a Project object
     *
     * @param   Receives the AgileZen project ID
     * @return  Project object
     * @see     alexandria.dashboard.entity.ProjectService
     * @author  Samuel Rodrigues
     * @author  Vinícius Rodrigues
     */
    def doProject(String id) {
        def json = getData("/api/v1/projects/${id}", 'metrics')
        def project = new Project(
            externalId: json.id,
            name: json.name,
            description: json.description,
            owner: json.owner.name
        )
		project.metrics=[
			throughput: json.metrics.throughput,
    		leadTime: json.metrics.leadTime,
    		cycleTime: json.metrics.cycleTime,
    		workTime: json.metrics.workTime,
    		waitTime: json.metrics.waitTime,
    		blockedTime: json.metrics.blockedTime,
   	 		efficiency: json.metrics.efficiency
			]
		println(json.toString())
		println("requisitando historias do projeto")
        getData("/api/v1/projects/${id}/stories").items.each {
            def story = new Story(
                externalId: it.id,
                text: it.text,
                size: it.size,
                priority: it.priority,
                deadline: it.deadline,
                status: it.status,
                phase: it.phase.name
            )
			println("historia ${it.id} com esforço ${it.size}")
            getData("/api/v1/projects/${id}/stories/${it.id}/tasks").items.each{
                def task = new Task(
                    externalId: it.id,
                    text: it.text,
                    status: it.status
                )
                task.save()
                story.addToTasks(task)
            }
            story.save()
            project.addToStories(story)
        }
        project.save()
        return project
    }


}
